import time

from flask import Flask, render_template, redirect, url_for, request, jsonify
import random
import xlwings
import mail
import database
import passcode
import flask_cors

########################################################################
# 初始化
app = Flask(__name__)

# 解决跨域

flask_cors.CORS(app, resources=r'/*')
# 维护待注册的用户和验证码
verification_dict = \
    {

    }
random.seed(159753)
# 记录接口的调用次数 1.随机不含行程卡 2.随机含行程卡 3.自定义 4.李达 5.更新日志
num_list = [0, 0, 0, 0, 0]
# 记录名言
words = []

# xlsx app初始化
x_app = xlwings.App(visible=False, add_book=False)
x_app.display_alerts = False
x_app.screen_updating = False

# 创建邮件对象
Mail = mail.MyMail()

# 创建数据库对象
Database = database.MyDataBase()


########################################################################

# 发送验证码 goal 为了什么而发验证码 dest 收件人邮箱地址
def verification_code(goal, dest):
    source = "1234567890QWERTYUIOPASDFGHJKLZXCVBNM"
    verification = ""
    for i in range(6):
        verification += source[random.randint(0, len(source) - 1)]
    body = \
        '''
<strong><p style="text-align: left">337WebServe</p></strong>
<p style="text-align: left">亲爱的用户:</p>
<p style="text-align: left">&nbsp&nbsp你的<span style="color: red">{}</span>验证码为<span style="color:green">{}.</span></p>
<p style="text-align: left">&nbsp&nbsp请妥善保管好你的验证码!</p>
<p></p>
<p></p>
<p style="text-align: right">337WebServe开发者致上!</p>
    '''.format(goal, verification)
    Mail.send(dest, '337WebServe验证码', body, 'html')
    return verification


# 获取新增用户id
def get_id():
    n_id = Database.all('web_data')[0]['id']
    tmp_id = n_id
    n_id += 1
    sql = Database.change('web_data', [{'id': n_id}, {}])
    return tmp_id


@app.route('/MadeLogin')
def made_login():
    return render_template('madepasscode.html')


@app.route('/MadePassCode', methods=['POST', 'GET'])
def made_pass_code():
    info_dict = {}
    user = {}
    if request.method == "POST":
        user = request.form
    elif request.method == 'GET':
        user = request.args
    for i in user:
        info_dict[i] = user[i]
    return passcode.result(info_dict)


# 1不包含行程卡  2 包含 3 李达
@app.route('/PassCodeRandom/<mode>')
def pass_code_random(mode):
    return passcode.pass_code_random(mode)


# 记录更新日志与Q&A
@app.route('/notes')
def notes():
    return render_template('notes.html')


# 跳出登录界面
@app.route('/pre_login')
def pre_login():
    return render_template('login/login.html', tips="如果要注册,直接点击登录会跳到注册页面")


# 验证登录
@app.route('/login', methods=['POST'])
def login():
    user = request.form
    info = Database.info('user_data', 'mail', user['mail'])
    if len(info) == 0:
        return render_template('login/login.html', tips="没有该邮箱,请注册!")
    print(info)
    if user['password'] != info[0]['password']:
        return render_template('login/login.html', tips="密码错误!")
    return render_template('login/home.html', info=info[0])


@app.route('/register_pre')
def register_pre():
    return render_template('login/register.html', tips="")


@app.route('/register', methods=['POST'])
def register():
    user = request.form
    if len(Database.info('user_data', 'mail', user['mail'])) == 0:
        verification_dict[user['mail']] = verification_code('注册', user['mail'])
        return render_template('login/register_verification.html', tips="验证码已发送!", mail=user['mail'])
    else:
        return render_template('login/register.html', mail=user['mail'])


@app.route('/check', methods=['POST'])
def check():
    user = request.form
    print(verification_dict)
    if user['verification'] != verification_dict[user['mail']]:
        return render_template('login/register_verification.html', mail=user['mail'], tips="输入的验证码错误!")
    verification_dict.pop(user['mail'])
    return render_template('login/user_add.html', mail=user['mail'])


@app.route('/user_add', methods=['POST'])
def user_add():
    user = request.form
    user_dict = {}
    for i in user:
        user_dict[i] = user[i]
    user_dict['id'] = get_id()
    Database.insert('user_data', user_dict)
    return 'success'


@app.route('/touch_me', methods=['POST'])
def touch_me():
    user = request.form
    body = \
        '''
337WebServe
开发者，你收到一条反馈
###############################
他/她(<span style="color: green">{}</span>)说:<span style="color: green">{}</span>
###############################
    '''.format(user['mail'], user['idea'])
    Mail.send('pangchao@337webserve.wecom.work', '来自{}的反馈'.format(user['mail']), body, 'html')
    return "谢谢你的反馈"


@app.route('/touch_me_pre')
def touch_me_pre():
    return render_template('touch/touch_me_pre.html')


@app.route('/search_pre')
def search_pre():
    return redirect(url_for('test/检索回答.html'))


@app.route('/search', methods=['post'])
def search():
    question = request.form['question']
    return render_template('test/显示回答.html', datas=Database.find('qa_data', 'question', question))
    # print(question)
    # print(Database.info('qa_data', 'question', question))
    # return 'success'
    # return Database.info('qa_data', 'question', question)


@app.route('/')
def index():
    return render_template('login/login.html', tips="")


def randName():
    surname = ['李', '任', '庞', '戚', '邱', '其', '黄', '林', '江']
    name = ['冯宇', '琦琛', '洲', '超', '美', '恺锟', '家琪', '俊杰', '富轩', '运坚']
    return surname[random.randint(0, len(surname) - 1)] + name[random.randint(0, len(name) - 1)]


@app.route('/rand_name', methods=['post', 'get'])
def rand_name():
    root = request.form['root']
    if root == "root":
        return jsonify({"name": randName()})
    return jsonify({"name": "fail"})


@app.route('/pre_code')
def pre_code():
    return render_template('test/码.html')


####################################################
# 博客相关的路由函数

@app.route('/database_create', methods=['post'])
def database_create():
    return 'success'


####################################################

if __name__ == '__main__':
    app.run()
